package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.jmp.autocofiguration.util.OssUtil2;
import com.jmp.base.dto.SunCodeCardResponse;
import com.jmp.base.dto.SunCodeCompanyRequest;
import com.jmp.feign.SunCodeFeign;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.entity.TokenEntity;
import one.stand.enums.AuditStateEnums;
import one.stand.mapper.*;
import one.stand.model.*;
import one.stand.request.CompanyRequest;
import one.stand.service.*;
import one.stand.service.CompanyService;
import one.stand.service.sys.SysDictValueService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private SunCodeFeign sunCodeFeign;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;


    @Autowired
    private BusinessCardMapperExt businessCardMapperExt;
    @Autowired
    private CompanyMapperExt companyMapperExt;
    @Autowired
    private CompanyCardMapperExt companyCardMapperExt;
    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private CompanyPlatformMapperExt companyPlatformMapperExt;
    @Autowired
    private CompanyPlatformChildMapper companyPlatformChildMapper;
    @Autowired
    private CompanyServiceService companyServiceService;

    @Override
    @Transactional
    public int addCompany(CompanyRequest request, boolean clientJxs, String platformKey) {
        log.info("添加公司：{}", JSON.toJSONString(request));
        AssertUtil.isFalse(StringUtils.isBlank(request.getCompanyLogo())
                || StringUtils.isBlank(request.getCompanyName())
                || request.getIndustryId() == null, ResultEnum.PARAM_CHECK);
        AssertUtil.isTrue(StringUtils.isNoneBlank(request.getPassword()), ResultEnum.FAIL, "请输入企业密令~!");

        // 判断是否有名片
        BusinessCard cardModel = businessCardBaseService.getByUserId(request.getId().intValue());
        AssertUtil.isNull(cardModel, ResultEnum.FAIL, "已有名片，无法创建公司");

        Company company = companyMapperExt.selectByName(request.getCompanyName());
        AssertUtil.isNull(company, ResultEnum.FAIL, "企业名称重复~!");

        Company companyModel = companyMapperExt.selectByUserId(request.getId().intValue());
        if (companyModel != null) {
            AssertUtil.isFalse(companyModel.getAuditState().equals(AuditStateEnums.APPLY_IN.getCode()), ResultEnum.FAIL, "您有待审核公司");
            AssertUtil.isFalse(companyModel.getAuditState().equals(AuditStateEnums.APPLY_FAIL.getCode()), ResultEnum.FAIL, "您有公司审核失败，请联系管理员");
            AssertUtil.fail(ResultEnum.FAIL, "已有公司，无法创建公司！");
        }

        Company inModel = new Company();
        BeanUtils.copyProperties(request, inModel);
        inModel.setCreateTime(DateUtil.currentDate());
        inModel.setUserId(request.getId().intValue());
        inModel.setAuditState(AuditStateEnums.APPLY_SUCCESS.getCode());// 默认审核通过
        inModel.setCompanyKey(RandomUtil.generateString(10));
        inModel.setAgentCompanyId(companyMapperExt.getAgentCompanyId(request.getCompanyKey()));
        inModel.setCompanyLogo(OssUtil2.getWebsiteUrlReplace(inModel.getCompanyLogo()));
        int r = companyMapperExt.insertSelective(inModel);
        AssertUtil.isTrue(r > 0, "创建企业失败");

        // 添加公司成功后把公司ID保存到用户表中
        userAdminService.updateUserRoleId(request.getId().intValue(), inModel.getCompanyId());

        // 创建公司购买名片服务记录： 3天有效期，1张名片
        companyServiceService.init(inModel.getCompanyId(), clientJxs);

        // 添加公司官网信息
        websiteService.saveEmpty(inModel.getCompanyId());

        // 加入企业平台
        String plaformCompanyKey = StringUtils.isNoneBlank(platformKey) ? platformKey : request.getCompanyKey();
        if (StringUtils.isNoneBlank(plaformCompanyKey)) {
            CompanyPlatform companyPlatform = companyPlatformMapperExt.select(plaformCompanyKey);
            AssertUtil.nonNull(companyPlatform, ResultEnum.FAIL, "禁止创建企业");
            addToPlatform(companyPlatform.getId(), inModel.getCompanyId());
        }

        // 更新Token公司信息
        TokenEntity entity = tokenService.getInfo(request.getToken());
        if (entity != null) {
            entity.setCId(inModel.getCompanyId().longValue());
            entity.setRoleId(inModel.getCompanyId());
        }
        tokenService.update(request.getId().intValue(), request.getToken(), entity);

        return inModel.getCompanyId();
    }

    @Override
    @Transactional
    public void remove(Integer companyId) {
        Company companyModel = new Company();
        companyModel.setCompanyId(companyId);
        companyModel.setIsDel(BaseModel.YES_DEL);
        companyMapperExt.updateByPrimaryKeySelective(companyModel);

        companyBaseService.reloadCompany(companyId);
    }

    @Override
    @Transactional
    public void update(Company company) {
        Company companyByName = companyMapperExt.selectByName(company.getCompanyName());
        AssertUtil.isFalse(Objects.nonNull(companyByName) && !companyByName.getCompanyId().equals(company.getCompanyId()), ResultEnum.FAIL, "企业名称重复~!");

        company.setIsDel(null);
        company.setUpdateTime(null);
        int i = companyMapperExt.updateByPrimaryKeySelective(company);
        AssertUtil.isTrue(i > 0, "企业修改失败");

        companyBaseService.reloadCompany(company.getCompanyId());
    }

    @Override
    @Transactional
    public void updateLevel(Integer companyId, Integer level) {
        Company company = new Company();
        company.setCompanyId(companyId);
        company.setCompanyLevel(level);
        companyMapperExt.updateByPrimaryKeySelective(company);

        companyBaseService.reloadCompany(company.getCompanyId());
    }

    @Override
    @Transactional
    public void saveCompanyCard(Integer companyId, Integer cardId) {
        CompanyCard companyCard = new CompanyCard();
        companyCard.setCompanyId(companyId);
        companyCard.setCardId(cardId);
        companyCardMapperExt.insertSelective(companyCard);
    }

    @Transactional
    @Override
    public void updateCompanyCard(Integer companyId, Integer cardId) {
        AssertUtil.nonNull(companyId, ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(cardId, ResultEnum.PARAM_CHECK);
        BusinessCard card = businessCardMapperExt.selectByPrimaryKey(cardId);
        AssertUtil.isTrue(Objects.nonNull(card) && card.getCompanyId().equals(companyId), ResultEnum.PARAM_CHECK);

        CompanyCard companyCard = companyCardMapperExt.selectByCompanyId(companyId);
        if (Objects.nonNull(companyCard) && !companyCard.getCardId().equals(cardId)) {
            CompanyCard companyCardUpdate = new CompanyCard();
            companyCardUpdate.setId(companyCard.getId());
            companyCardUpdate.setCardId(cardId);
            companyCardMapperExt.updateByPrimaryKeySelective(companyCardUpdate);
        }
    }

    @Override
    public Integer getCompanyCard(Integer companyId) {
        CompanyCard companyCard = companyCardMapperExt.selectByCompanyId(companyId);
        if (Objects.isNull(companyCard)) {
            Company company = companyMapperExt.selectByPrimaryKey(companyId);
            BusinessCard businessCard = businessCardBaseService.getByUserId(company.getUserId());
            if (Objects.nonNull(businessCard)) {
                saveCompanyCard(companyId, businessCard.getCardId());
                return businessCard.getCardId();
            }
            return null;
        }
        return companyCard.getCardId();
    }

    @Override
    public Integer getCompanyCardById(Integer id) {
        CompanyCard companyCard = companyCardMapperExt.selectByPrimaryKey(id);
        return Objects.nonNull(companyCard) ? companyCard.getCardId() : null;
    }

    @Override
    public String getSuncode(Integer companyId) {
        //card
        CompanyCard companyCard = companyCardMapperExt.selectByCompanyId(companyId);
        //logo
        CompanyPlatform companyPlatform = companyPlatformMapperExt.selectPlatformByCompanyId(companyId);
        String companyKey = Objects.nonNull(companyPlatform) ? companyPlatform.getCompanyKey() : null;
        SysDictValue sysDictValue = sysDictValueService.getNullDefault(SysDictValueService.Type.CONFIG, companyKey, SysDictValueService.TypeName.suncode_company_logo.name());
        String logo;
        if (Objects.nonNull(sysDictValue)) {
            logo = sysDictValue.getValue();
        } else {
            Company company = companyMapperExt.selectByPrimaryKey(companyId);
            logo = company.getCompanyLogo();
        }
        //sunCode
        ResultModel<SunCodeCardResponse> sunCodeCardResponseResultModel = sunCodeFeign.company(SunCodeCompanyRequest.builder()
                .cardId(companyCard.getId() * -1)
                .companyId(companyId)
                .logo(logo)
                .build());
        AssertUtil.isTrue(sunCodeCardResponseResultModel);
        return sunCodeCardResponseResultModel.getData().getCodeUrl();
    }

    @Override
    public Company get(Integer companyId) {
        return companyMapperExt.selectByPrimaryKey(companyId);
    }

    @Override
    public Company getByUserId(Integer userId) {
        Company company = companyMapperExt.selectByUserId(userId);
        return company;
    }

    /**
     * 企业平台
     */
    private void addToPlatform(Integer platformId, Integer companyId) {
        CompanyPlatformChild companyPlatformChild = new CompanyPlatformChild();
        companyPlatformChild.setPlatformId(platformId);
        companyPlatformChild.setCompanyId(companyId);
        companyPlatformChildMapper.insertSelective(companyPlatformChild);
    }
}
